package com.finger.gulimall.member.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finger.common.utils.PageUtils;
import com.finger.common.utils.Query;
import com.finger.common.utils.R;
import com.finger.gulimall.member.dao.MemberDao;
import com.finger.gulimall.member.entity.MemberEntity;
import com.finger.gulimall.member.exception.LoginException;
import com.finger.gulimall.member.exception.PhoneExistsExcepiton;
import com.finger.gulimall.member.feign.OrderRemoteService;
import com.finger.gulimall.member.interceptor.LoginInterceptor;
import com.finger.gulimall.member.service.MemberService;
import com.finger.gulimall.member.vo.LoginVo;
import com.finger.gulimall.member.vo.OrderVo;
import com.finger.gulimall.member.vo.RegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Autowired
    OrderRemoteService orderRemoteService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(RegistVo registVo) {
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setUsername(registVo.getUsername());
        Integer countName = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", registVo.getUsername()));

        if(countName>0){
            throw new LoginException("该用户名已存在");
        }
        Integer countPhone = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", registVo.getPhone()));
        if (countPhone>0){
            throw new PhoneExistsExcepiton("该手机已被使用");
        }else{
            // 盐值加密
            // BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            memberEntity.setPassword(encoder.encode(registVo.getPassword()));
            // TODO 查重复手机号
            memberEntity.setMobile(registVo.getPhone());
            memberEntity.setCreateTime(new Date());
            // TODO 动态查找数据库获取默认会员等级
            memberEntity.setLevelId(3L);
            baseMapper.insert(memberEntity);
        }

    }

    @Override
    public Boolean queryNameExists(String name) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", name));
        return count>0;
    }

    @Override
    public MemberEntity login(LoginVo loginVo) {

        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",loginVo.getLoginacct()).or().eq("mobile",loginVo.getLoginacct());
        MemberEntity memberEntity = baseMapper.selectOne(queryWrapper);
        if(memberEntity==null){
            return null;
        }

        boolean matches = encoder.matches(loginVo.getPassword(), memberEntity.getPassword());
        String encode = encoder.encode(memberEntity.getPassword());
        log.debug("加密过后的密码："+encode);
        if(matches){
            return memberEntity;
        }else{
            return null;
        }
    }

    @Override
    public PageUtils getOrders(Integer page, Integer limit) {

        Map<String, Object> map = new HashMap<>();
        map.put("page", page.toString());
        map.put("limit", limit.toString());
        map.put("memberId", LoginInterceptor.loginMember.get().getId());
        R r = orderRemoteService.getOrderItems(map);
        if (r.getCode() != 0) {
            throw new RuntimeException("订单系统异常");
        }
        System.out.println(JSON.toJSONString(r));
        Page<OrderVo> data = r.getData(new TypeReference<Page<OrderVo>>() {
        });
        return new PageUtils(data);
    }
}